<?php
require_once "../../vendor/workerman/workerman/Autoloader.php";

use Workerman\Connection\TcpConnection;
use Workerman\Timer;
use Workerman\Worker;

//Worker 默认支持的6种协议 http websocket,tcp,udp,unix,text
/*
$worker1 = new Worker("http://0.0.0.0:12138");
$worker2 = new Worker("websocket://0.0.0.0:12139");
$worker3 = new Worker("tcp://0.0.0.0:12140");
$worker4 = new Worker("udp://0.0.0.0:12141");
$worker5 = new Worker("unix:///tmp/my_unix.sock");
$worker6 = new Worker("text://0.0.0.0:12143");
*/

//Worker 多实例
/*
$worker1 = new Worker("websocket://0.0.0.0:12138");
$worker1->count = 4;//设置有多少个子进程
$worker1->name="websocket";//设置worker 实例名称，默认为none
$worker1->onWorkerStart = function ($worker1){
    echo "=worker1=进程id===".$worker1->id.PHP_EOL;
};

$worker2 = new Worker("http://0.0.0.0:12139");
$worker2->count = 3;//设置有多少个子进程
$worker2->name = "http";//设置worker 实例名称，默认为none
$worker2->onWorkerStart = function ($worker2){
    echo "=worker2=进程id===".$worker2->id.PHP_EOL;
};

$worker3 = new Worker("text://0.0.0.0:12137");
$worker3->count = 2;//设置有多少个子进程
$worker3->name = "http";//设置worker 实例名称，默认为none
$worker3->protocol = "Workerman\\Protocols\\Http";//设置协议
$worker3->transport = 'udp';
$worker3->onWorkerStart = function ($worker3){
    echo "=worker3=进程id===".$worker3->id.PHP_EOL;
};
*/

// 设置worker 是否平滑启动 默认为true
/*
$worker = new Worker("tcp://0.0.0.0:12138");
$worker->count=2;
$worker->reloadable=true;
$worker->onWorkerStart = function ($worker){
   echo "Worker starting".PHP_EOL;
};
*/

$worker = new Worker("tcp://0.0.0.0:9999");
$worker->reloadable=true;
$worker->count=5;
//设置Worker子进程启动时的回调函数，每个子进程启动时都会执行。
$worker->onWorkerStart = function ($worker){
    echo "Worker {$worker->id} starting...\n";

    $inner_worker = new Worker("http://0.0.0.0:19999");
    $inner_worker->reusePort = true;
    $inner_worker->onMessage = 'onMessage';
    $inner_worker->listen();

};

//当客户端与Workerman建立连接时(TCP三次握手完成后)触发的回调函数。每个连接只会触发一次onConnect回调
$worker->onConnect=function (TcpConnection $connection){
    echo "new connection from ip " . $connection->getRemoteIp() . "\n";
};

//当客户端通过连接发来数据时(Workerman收到数据时)触发的回调函数
$worker->onMessage= "onMessage";

function onMessage (TcpConnection $connection,$data){
  var_dump($data);
  $connection->send('receive success');
};

//客户端连接与Workerman断开时触发的回调函数。不管连接是如何断开的，只要断开就会触发onClose。每个连接只会触发一次onClose。
$worker->onClose=function (TcpConnection $connection){
    echo $connection->getRemoteAddress()."===connection closed\n";
};

//可以利用TcpConnection::$defaultMaxSendBufferSize 设置所有连接默认缓冲区的大小，例如代码：
// 设置所有连接的默认应用层发送缓冲区大小，单位字节
//TcpConnection::$defaultMaxSendBufferSize = 2*1024*1024;
$worker->onBufferFull=function (TcpConnection $connection){
    echo "bufferFull and do not send again\n";
};

$worker->onBufferDrain = function (TcpConnection $connection){
    echo "buffer drain and continue send\n";
};

$worker->onError=function (TcpConnection $connection, $code, $msg){
    echo "error $code $msg\n";
};

Worker::runAll();